<?php
/**
 * Created by PhpStorm.
 * User: l
 * Date: 2018/10/30
 * Time: 13:13
 */
use app\assets\AppAsset;
use app\common\CommonHelper;

$base = Yii::$app->request->baseUrl;
AppAsset::addCss($this,$base . '/app/css/vest-list.css');

AppAsset::addCss($this,$base . '/css/jquery.Jcrop.css');
AppAsset::addScript($this,$base . '/js/jquery.Jcrop.min.js');
AppAsset::addScript($this,$base . '/app/js/jedate.js');
AppAsset::addScript($this,$base . '/app/js/app-js.js');
AppAsset::addCss($this,$base . '/app/css/skin/jedate.css');


$model = new CommonHelper();
$baseUrlHead  = $model->getIp();

$tomorrowDate = $model->getTomorrowDateHI();
$yesterdayDate = $model->getYesterdayDateHI();
?>

<div class="search-box">
    <div class="button-div" style="margin-left: 1.6rem" onclick="setAdmin()">新增</div>
</div>

<div class="dialog-topic" id="addAdmin" hidden="hidden">
    <div class="topic-box">
        <p style="margin-bottom:1.65rem ;">添加员工</p>
        <div>账号: <input id="staffPhone" style="margin-bottom: 1rem;" placeholder="输入员工手机号" maxlength='11' oninput = "value=value.replace(/[^\d]/g,'')"></div>
        <div>密码: <input type="password" id="staffPass" style="margin-bottom: 1rem;" placeholder="输入员工密码"></div>

        <div class="footer-div">
            <div class="button-div" onclick="addStaffController.createStaff()">确定</div>
            <div class="button-div" style="margin-left: 1.5rem" onclick="hideAdmin()">取消</div>
        </div>
    </div>
</div>

<div class="dialog-topic" id="editJurisdiction" hidden="hidden">
    <div class="topic-box">
        <p style="margin-bottom:1.65rem ;">编辑员工</p>
        <div>权限更改: <select id="jurisdictionName" style="margin: 1rem;"></select></div>

        <div class="footer-div">
            <div class="button-div" id="jurisdictionEdit">确定</div>
            <div class="button-div" style="margin-left: 1.5rem" onclick="hideEdit()">取消</div>
        </div>
    </div>
</div>

<div class="table-box" style="background: none">
    <table id="table" style="background: #FFFFFF;"></table>
</div>

<script>
    //初始化表格设置
    $('#table').bootstrapTable({
        toolbar: '#toolbar',        //工具按钮用哪个容器
        clickToSelect: true,//点击行即可选中单选/复选框
        singleSelect: false,//复选框只能选择一条记录
        search: false,//是否显示右上角的搜索框
        striped: true,      //是否显示行间隔色
        cache: false,            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sidePagination: "server", //服务端处理分页
        pagination: true,     //是否显示分页（*）
        sortable: false,           //是否启用排序
        sortOrder: "asc",          //排序方式
        method: 'GET',      //请求方式（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 10,      //每页的记录行数（*）
//        pageList: [10, 20, 50, 100],  //可供选择的每页的行数（*）
        cardView: false,          //是否显示详细视图
        queryParams:setParams,
        uniqueId:'admin_id',
        url:'staff',
        responseHandler:dataProcess,
        columns: [{
            field: 'admin_id',
            align: 'center',
            valign: 'middle',
            title: '员工ID'
        },{
            field: 'mobile',
            align: 'center',
            valign: 'middle',
            title: '员工电话'
        },{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '职位',
            formatter:function(value,row, index) {
                if (row.type == 1) {
                    return "经理";
                } else if (row.type == 2) {
                    return "营销";
                } else if (row.type == 3) {
                    return "普通";
                } else if (row.type == 0) {
                    return "超级管理员";
                } else {
                    return "所有";
                }
            }
        },{
            field: 'is_deleted',
            align: 'center',
            valign: 'middle',
            title: '状态',
            formatter:function(value, row, index) {
                if (row.is_deleted == 0) {
                    return "正常";
                } else {
                    return "下架";
                }
            }
        },{
            field: '',
            align: 'center',
            valign: 'middle',
            title: '操作',
            formatter:function(value,row, index) {
                var html = "";
                if (row.is_deleted == 0) {
                    html = '<div style="display:inline-block" class="btn_cancel" onclick="editDeleted('+ row.admin_id +', 1)">下架</div> <div style="display:inline-block" class="btn_cancel" onclick="showEdit('+ row.admin_id +')">编辑</div> <div style="display:inline-block" class="btn_cancel" onclick="editPwd('+ row.admin_id +')">重置密码</div>';
                } else {
                    html = '<div style="display:inline-block" class="btn_cancel" onclick="editDeleted('+ row.admin_id +', 0)">上架</div> <div style="display:inline-block" class="btn_cancel" onclick="showEdit('+ row.admin_id +')">编辑</div> <div style="display:inline-block" class="btn_cancel" onclick="editPwd('+ row.admin_id +')">重置密码</div>';
                }

                return html;
            }
        }]
    });

    function dataProcess(res){
        var data = res;
        return {
            'rows':data.rows,
            'total':data.total
        }
    }

    var payType = -1;

    function setParams(params){
        var start_date = $('#datebut').val(); //按日期搜索
        var end_date = $('#datebut2').val();

        if (start_date && start_date != undefined && end_date && end_date != undefined){
            params.start_date = start_date;
            params.end_date = end_date;
        }

        if(payType != -1)
            params.pay_type = payType;

        var cityCode = $("#cityID").val();
        if(cityCode != -1)
            params.city_code = cityCode;

        var content = $("#nameId").val();
        if (content && content != undefined && content.length > 0)
            params.user_name = content;

        return params;
    }

    var createVestController = {
        createVestApi:'<?= $baseUrlHead?>Hotcity/v1/users',
        createVestFunc : function(){

            var mobile = "168168" + Math.round(new Date().getTime()/1000).toString();

            var userAvatar = $("#img").attr("src");
            if(userAvatar.indexOf("http") == -1){
                alert("请上传头像");
                return;
            }

            var userName = $("#vestName").val();
            if(userName.length == 0){
                alert("请输入昵称");
                return;
            }

            var userAge = $("#vestAge").val();
            if(userAge.length == 0){
                alert("请输入年龄");
                return;
            }

            var userSex = $("#sexID").val();

            var cityCode = $("#cityID").val();

            var param = {
                mobile:mobile,
                user_avatar: userAvatar,
                user_nickname:userName,
                user_age:parseInt(userAge).toString(),
                user_lng:"120",
                user_lat:"30",
                user_sex:userSex,
                city_code:cityCode
            };

            $(".loading-area").show();
            sendAjax(this.createVestApi,"POST",param,false,function(res){
               if(res.code != 0){
                   location.reload();
               }else
                   alert(res.msg);
            });
        }
    }

    // 显示添加员工页面
    function setAdmin() {
        $("#addAdmin").show();
    }

    // 隐藏添加页面
    function hideAdmin(){
        $("#addAdmin").hide();
    }

    // 添加员工
    var addStaffController = {
        addStaff : 'add-staff',

        createStaff : function() {
            var mobile = $('#staffPhone').val();
            if (mobile.length == 0) {
                alert('请输入手机号');
                return;
            }

            var password = $('#staffPass').val();
            if (password.length == 0) {
                alert('请输入密码');
                return;
            }

            params = {
                mobile : mobile,
                password : password
            }

            $(".loading-area").show();
            sendAjax(this.addStaff, 'POST', params, false, function(res){
                var row = JSON.parse(res);

                if (row.code == 0) {
                    location.reload();
                } else {
                    alert(row.msg);
                }
            });
        }
    }

    // 修改员工状态
    function editDeleted(adminId, status){
        staff = "edit-staff";
        if (confirm('确认修改该员工状态？')) {
            var param = {
                admin_id : adminId,
                is_deleted : status
            };

            sendAjax(this.staff,"POST",param,false,function(res){
                var row = JSON.parse(res);
                if(row.code == 0){
                    $('#table').bootstrapTable('refresh');
                }else {
                    alert(row);
                }
            });
        }
    }

    // 重置员工密码
    function editPwd(adminId){
        staff = "edit-staff";
        if (confirm('确认重置该员工的密码？')) {
            var param = {
                admin_id : adminId,
                password : 123456
            };

            sendAjax(this.staff,"POST",param,false,function(res){
                var row = JSON.parse(res);
                if(row.code == 0){
                    $('#table').bootstrapTable('refresh');
                }else {
                    alert(row);
                }
            });
        }
    }

    // 显示编辑页面
    function showEdit(adminId) {
        staff = "show-staff";
        var param = {
            admin_id : adminId,
        }

        sendAjax(this.staff,"POST",param,false,function(res){
            var row = JSON.parse(res);
            console.log(row);
            var type = "";
            if (row.type == 3) {
                var type = "普通";
                $("#jurisdictionName").html("<option value='"+ row.type +"'>"+ type +"</option> <option value='2'>营销</option> <option value='1'>经理</option> <option value='0'>超级管理员</option>" );

            } else if (row.type == 2) {
                var type = "营销";
                $("#jurisdictionName").html("<option value='"+ row.type +"'>"+ type +"</option> <option value='3'>普通</option> <option value='1'>经理</option> <option value='0'>超级管理员</option>" );

            } else if (row.type == 1) {
                var type = "经理";
                $("#jurisdictionName").html("<option value='"+ row.type +"'>"+ type +"</option> <option value='3'>普通</option> <option value='2'>营销</option> <option value='0'>超级管理员</option>" );

            } else {
                var type = "超级管理员";
                $("#jurisdictionName").html("<option value='"+ row.type +"'>"+ type +"</option> <option value='3'>普通</option> <option value='2'>营销</option> <option value='1'>经理</option>" );

            }

            // 执行员工编辑
            $("#jurisdictionEdit").on("click", function () {
                var createStaffApi = 'edit-staff';
                var type = $("#jurisdictionName").val();

                var param = {
                    admin_id : row.admin_id,
                    admin_type : type
                };

                $(".loading-area").show();
                sendAjax(createStaffApi, "POST", param, false, function(data){
                    if (data.code != 0) {
                        location.reload();
                    } else {
                        alert(data.msg);
                    }
                });
            });

            $('#editJurisdiction').show();
        });
    }

    // 隐藏编辑页面
    function hideEdit() {
        $("#editJurisdiction").hide();
    }

</script>
